/**
 * @file image.js
 * @author wxf
 * @date 2019/03/07
 */

/**上传文件**/
var Utils = {
  /**
   * 伪文件选择框点击事件，触发真的文件选择框点击事件
   * @param {Object} that 文件选择框选择按钮对象
   */
  chooseFile: function (that) {
    $(that).parent().parent().children('input:first-child').click();
  },


  /**
   * 真文件选择框的change事件（此处将文件名显示到伪文件选择框）
   * @param {Object} that 真的文件选择框的 document 对象
   */
  afterChooseFile: function (that) {
    var viewInput = $(that).next('input');
    var name = that.files.length ? that.files[0].name : '';
    viewInput.val(name);
  },

  /**
   * 这里是yupeng自己新写 afterChooseFile 的，在真实框中内容改变之后就要检测是否相同并且上传，然后要返回id
   **/
  afterChooseFileUpload: function () {
    // var viewInput = $(that).next('input');
    // var name = that.files.length ? that.files[0].name : '';
    // viewInput.val(name);
      var that = $("#true-file");
    var files = $(that).prop('files');
    if (files.length) {
      uploadFile(files[0]);
    } else {
      $.notify({
        type: 'danger',
        message: gettext('Please select a file.')
      });
    }
  },

  /**
   * 判断当前输入框中的值是否与已有值重复（最多只能有两级），若重复会弹出错误通知
   * @param {Object} $input 所对应的输入框的 jQuery 对象
   * @param {boolean=false} group 是否为添加 group，默认为false
   * @returns {boolean} 能为 true，不能为 false
   */
  canAppend: function ($input, group) {
    if (!$input.val().trim()) {
      $.notify({type: 'danger', message: gettext('Option/Group name cannot be null or spaces.')});
      Utils.flashBadField($input, '.t-field');
      return false;
    }

    group = group || false;
    var $root, el;
    if (group) {
      $root = $input.parents('ul:first');
      el = '>li.group>b';    // group 只要同意层级分组名不同即可
    } else {
      $root = $input.parents('ul.t-field-content-extra:first');
      el = 'li.option';     // 选项需要全局都不同
    }

    var lis = $root.find(el);
    for (var i = 0; i < lis.length; i++) {
      if ($(lis[i]).text().trim() === $input.val().trim()) {
        $.notify({type: 'danger', message: gettext('Option/Group name duplicate')});
        Utils.flashBadField($input, '.t-field');
        return false;
      }
    }
    return true;
  }
  ,
  /**
   * 在输入框中输入值后按下 enter 键添加 option
   * @param {Object} e 键盘 key up 事件
   * @param {Object} that 对应输入框 document 对象
   */
  appendOptionByKeyUp: function (e, that) {
    var $input = $(that);
    if (e.which === 13 && Utils.canAppend($input)) {
      $input.parent().parent().before(TemplateFactory._CHOICE_LI({type: 'option', name: that.value.trim()}));
      $input.val('').focus();  // 可添加则清空输入并 focus
    }
  }
  ,
  /**
   * 点击添加选项按钮添加对应选项
   * @param {Object} that 对应输入框 document 对象
   */
  appendOptionByClick: function (that) {
    var $that = $(that);
    var $input = $that.prev().children('input:first-child');
    if (Utils.canAppend($input)) {
      $(that).parent().before(TemplateFactory._CHOICE_LI({type: 'option', name: $input.val()}));
      $input.val('').focus();  // 可添加则清空输入并 focus
    }
  }
  ,
  /**
   * 点击添加分组按钮添加对应分组
   * @param {Object} that 对应输入框 document 对象
   */
  appendGroup: function (that) {
    var $that = $(that);
    var $input = $that.prev().prev().children('input:first-child');
    if (Utils.canAppend($input, true)) {
      var $groupLi = $(TemplateFactory._CHOICE_LI({type: 'group', name: '<b>' + $input.val() + '</b>'}));
      $groupLi.append(TemplateFactory._CHOICE_SCOPE({addGroup: false}));
      $that.parent().before($groupLi);
      $input.val('').focus();  // 可添加则清空输入并 focus
    }
  },


   uploadFile: function (input) {
      var class_asset_id = vrclass_id;
      if($("#ta-title").val() === "test"){
          class_asset_id = vrclassTest_id;
      }
      else
          class_asset_id = vrclass_id;
      var $input = $(input);
      var urls = $input.data('urls') || [];
      if (urls.length) {
          Utils.deleteFile(urls);
          $input.data('urls', []);
      }
      if (input.files.length === 0) {
          $input.data('urls', []);
          return;
      }
      var formData = new FormData(),
          fLength = 0;  // 为辣鸡 safari/ie/edge 设置的flag;
      formData.append('class_asset_id', class_asset_id);
      $.each(input.files, function (i, file) {
          formData.append('files', file);
          fLength += 1;
      });
      if (fLength < 1) {
          return;   // 说明formData中没有任何数据
        }
      $('body').preloader({
          text: gettext('Uploading...'),
          percent: '0'
      });
      $.ajax({
          url: Urls.resolve('mlplatform_api_v2:asset_list'),
          data: formData,
          processData: false,
          contentType: false,
          type: 'POST',
          xhr: function () {
              var myXhr = $.ajaxSettings.xhr();
              if (myXhr.upload) {
                  myXhr.upload.addEventListener('progress', function (e) {
                      if (e.lengthComputable) {
                          var complete = (e.loaded / e.total * 100 | 0);
                          $('body').preloader('update', {
                              percent: complete.toString(),
                              text: gettext('Uploading...')
                          });   // 更新loading进度
                      }
                  }, false);
              }
              return myXhr;
          },
          success: function (data) {
              $("#image-count").text(data.data.num_of_pictures);
          },
          error: function () {
              alert(gettext('Sadly, an error occurred when send your request.💀'));
          }
      }).done(function (resp) {
          $("#image_show").append(show_OneImage(class_asset_id));
          // show_OneImage(resp);
      }).fail(function (data) {
          window._jqHandled = true;
      }).always(function () {
          $('body').preloader('remove');
      });
  },
};

function uploadFile(file) {
    var class_asset_id = vrclass_id;
    if($("#ta-title").val() === "test"){
        class_asset_id = vrclassTest_id;
    }
    else
        class_asset_id = vrclass_id;
    var formData = new FormData();
    formData.append('files', file);
    formData.append('class_asset_id',class_asset_id);

    $('body').preloader({
        text: gettext('Uploading...'),
        percent: '0'
    });
    $.ajax({
        url: Urls.resolve('mlplatform_api_v2:asset_list'),
        data: formData,
        processData: false,
        contentType: false,
        type: 'POST',
        xhr: function () {
            var myXhr = $.ajaxSettings.xhr();
            if (myXhr.upload) {
                myXhr.upload.addEventListener('progress', function (e) {
                    if (e.lengthComputable) {
                        var complete = (e.loaded / e.total * 100 | 0);
                        $('body').preloader('update', {
                            percent: complete.toString(),
                            text: gettext('Uploading...')
                        });   // 更新loading进度
                    }
                }, false);
            }
            return myXhr;
        },
        success: function (data) {
            alert(gettext('Upload Successfully！'));
      },
      error: function () {
        alert(gettext('Sadly, an error occurred when send your request.💀'));
      }
    }).done(function (resp) {
        $("#image-count").text(resp.data.num_of_pictures);
        $("#image_show").append(show_OneImage(class_asset_id));
        // show_OneImage(resp);
    }).fail(function (data) {
        window._jqHandled = true;
    }).always(function () {
        $('body').preloader('remove');
    });
}

function show_OneImage(that) {
    var classid = parseInt(that);
    $.get(Urls.resolve('mlplatform_api_v2:class_asset_one'), {
        'class_asset_id':classid,
    }).done(function (data) {
        $("#image-count").text(data.data.num_of_pictures);
        var dsScope = $('#image_show');
        dsScope.empty();
        show_AllImage(data);
    }).fail(function () {
        window._jqHandled = true;
    });
}

function show_AllImage(data) {
    $.each(data.data.images_path,function () {
        var imageName = this.split("/")[1];
        var obj = '<div class="col-lg-2 col-md-2 col-sm-2 col-xs-12" style="height: 200px;width: 200px">'+
            '   <img class="img-thumbnail" width="150" height="150" src="/media/'+ this +'" alt="">' +
            '   <h4 class="services-title">'+ imageName +'</h4>'+
            '</div>';
        $("#image_show").append(obj);
    });

}

function create_Task() {
    $.requestJSON({
      url: Urls.resolve('mlplatform_api_v2:vr_task_list'),
      method: 'POST',
      silentError: true,
        onSuccess: function (data) {
          vrtask_id = data.data.vrtask_id;
          vrclassTest_id = data.data.test_class_id;
          show_Class();
          $("#new_task").show();
          $("#task_div").show();
          $("#submit-task").show();
          // createTest(data);
        },
        onError:function (data) {
          $.showModal({
              title: gettext('ERROR') + ' ' + data.code,
              message: gettext('An error has occurred! Please check your data and try again.')
          });
        }
    });
}

function create_Class(class_id) {
    $.requestJSON({
      url: Urls.resolve('mlplatform_api_v2:class_asset_one'),
      method: 'PATCH',
      data:{
        class_asset_id: class_id,
        title: $("#ta-title").val(),
        tag: null,
        description: $("#ta-abstract").val()
      },
      silentError: true,
        onSuccess: function (data) {
          show_Class();
          // create_class(data);
          // var fmts = gettext('Successfully created the class!\nYou can continue to add new class.');
          //     $.showModal({
          //       title: gettext('Class created!'),
          //       message: interpolate(fmts)
          //     });
        },
        onError:function (data) {
          $.showModal({
              title: gettext('ERROR') + ' ' + data.code,
              message: gettext('An error has occurred! Please check your data and try again.')
          });
        }
    });
}
// 查询某个任务，显示分类
function acquire_result(callback) {
    $.get(Urls.resolve('mlplatform_api_v2:vr_task_one'), {
        'vrtask_id':vrtask_id,
    }).done(function (data) {
        console.log(data);
        callback(data);
    }).fail(function () {
    window._jqHandled = true;
    });
}

function show_Class() {
    acquire_result(function (data) {
            set_hasClass(data);
        }
    );
}
//显示该任务下的所有分类
function set_hasClass(data) {
    $("#createTestclass").empty();
    $.each(data.data.classes, function () {
        var obj='<div class="cla col-lg-2 col-md-2 col-sm-2 col-xs-12" id='+ this['id'] +'  name='+ this['class_title'] +' '+
            '    data-toggle="modal" onclick="show_Oneclass(this)" style="cursor:pointer">'+
            '    <div class="services-group">'+
            '        <p class="services-icon" style="text-align:center;opacity: 0">'+
            '            <span class="fa fa-plus fa-5x"></span>'+
            '        </p>'+
            '        <h4 class="services-title">'+ this['class_title'] +'('+ this['num_of_pictures'] +')</h4>'+
            '    </div>'+
            '</div>';
    $("#createTestclass").append(obj);
    });
}
//点击一个类之后 显示具体信息
function show_Oneclass(that) {
    var classid = parseInt(that.id);
    vrclass_id = classid;
    $.get(Urls.resolve('mlplatform_api_v2:class_asset_one'), {
        'class_asset_id':classid,
    }).done(function (data) {
        if(data.data.class_title === 'test')
        {
            $("#ta-title").attr("disabled",true);
        }
        else{
            $("#ta-title").attr("disabled",false);
        }
        $("#new_class").show();
        $("#class_div").show();
        $("#ta-title").val(data.data.class_title);
        $("#ta-abstract").val(data.data.description);
        $("#image-count").text(data.data.num_of_pictures);
        $("#upload").val('');
        var dsScope = $('#image_show');
        dsScope.empty();
        show_AllImage(data);
    }).fail(function () {
        window._jqHandled = true;
    });
}

function save_Task() {
    $.requestJSON({
          url: Urls.resolve('mlplatform_api_v2:vr_task_one'),
          method: 'PATCH',
          data:{
            vrtask_id: vrtask_id,
            title: $("#t-title").val(),
            description: $("#t-abstract").val()
          },
          silentError: true,
            onSuccess: function (data) {
              window._committed = true;
              start_Train();
            },
            onError:function (data) {
              $.showModal({
                  title: gettext('ERROR') + ' ' + data.code,
                  message: gettext('An error has occurred! Please check your data and try again.')
              });
            }
        });
}

function start_Train() {
    if ($("#t-title").val() === "" || $("#t-abstract").val() === "") {
            $.showModal({
                title: gettext('ERROR'),
                message: gettext('The task name or abstract is empty! Please check your data and try again.')
            });
        }
        else {
            $.get(Urls.resolve('mlplatform_api_v2:vrtask_start'), {
                'vrtask_id': vrtask_id,
            }).done(function (data) {
                var fmts = gettext('Successfully start the task!You can view in the task lists.');
                  $.showModal({
                    title: gettext('Task start!'),
                    message: interpolate(fmts)
                  });
                // console.log(data);
                // callback(data);
            }).fail(function () {
                window._jqHandled = true;
            });
        }
}


var vrtask_id;
var vrclass_id;
var vrclassTest_id;

$(function () {
    $("#create_model").click(function () {
        $.requestJSON({
          url: Urls.resolve('mlplatform_api_v2:class_asset_list'),
          method: 'POST',
          data:{
            vrtask_id:vrtask_id
          },
          silentError: true,
            onSuccess: function (data) {
              vrclass_id = data.data;
              $("#new_class").show();
              $("#class_div").show();
              $("#ta-title").attr("disabled",false);
              $("#ta-title").val('');
              $("#ta-abstract").val('');
              $('#image_show').empty();
              $("#image-count").text(0);
            },
            onError:function (data) {
              $.showModal({
                  title: gettext('ERROR') + ' ' + data.code,
                  message: gettext('An error has occurred! Please check your data and try again.')
              });
            }
        });
    });

    /**上传文件*/
    $("#upload-file").click(function () {
        // var filein = $("#true-file");
        // Utils.afterChooseFileUpload(filein);
    });


    $("#save-template").click(function () {
        // if (!$.vf.validate()) {
        //     return;
        // }
        if($("#ta-title").val() === ""||$("#ta-abstract").val() === ""){
            $.showModal({
                  title: gettext('ERROR'),
                  message: gettext('The class name or abstract is empty! Please check your data and try again.')
              });
        }
        else{
            if($("#ta-title").val() === "test"){
                create_Class(vrclassTest_id);
            }
            else{
                create_Class(vrclass_id);
            }
            $("#new_class").hide();
            $("#class_div").hide();
        }
    });

    $("#cancel_class").click(function (e) {
        alert('Delete!');
        var ccel_classid;
        if($("#ta-title").val() === "test"){
            ccel_classid = vrclassTest_id;
        }
        else{
            ccel_classid = vrclass_id;
        }
        $.requestJSON({
          url: Urls.resolve('mlplatform_api_v2:class_asset_one'),
          method: 'PATCH',
          data:{
            class_asset_id: ccel_classid,
            save: false
          },
          silentError: true,
            onSuccess: function (data) {
              show_Class();
              $("#new_class").hide();
              $("#class_div").hide();
              // alert('Delete!');
            },
            onError:function (data) {
              $.showModal({
                  title: gettext('ERROR') + ' ' + data.code,
                  message: gettext('An error has occurred! Please check your data and try again.')
              });
            }
        });
    });

    window._committed = false;   // 保存状态
    // 设置窗口关闭确认事件
    $(window).bind('beforeunload', function (e) {
        if (!window._committed) {
            return 'Are you sure to leave this page?';
        }
    });
    $(window).bind("beforeunload", function (e) {
        // 退出之前删除所有未保存但已上传的数据
        if(!window._committed){
            $.requestJSON({
              url: Urls.resolve('mlplatform_api_v2:vr_task_one'),
              method: 'PATCH',
              data:{
                vrtask_id: vrtask_id,
                save: false
              },
              silentError: true,
                onSuccess: function (data) {
                },
                onError:function (data) {
                  $.showModal({
                      title: gettext('ERROR') + ' ' + data.code,
                      message: gettext('An error has occurred! Please check your data and try again.')
                  });
                }
            });
        }
    });

    $('#ta-title').blur(function () {
		var that = this;
		if($("#ta-title").val() === "test") {//ajaxValidation内容是ajax校验，返回bool值
		    $.showModal({
                title: gettext('ERROR'),
                message: gettext('The class of test is already exits.Please check your data and try again.')
            });
			// alert("The class of 'test' is already exits.Please check your data and try again.");//最好用自定义的提示方式
			setTimeout(function () {
				$(that).focus();
				$(that).select();
				},100);
		}
	});

    $("#new_class").hide();
    $("#new_task").hide();
    $("#task_div").hide();
    $("#class_div").hide();
    $("#submit-task").hide();
    // start train
    $("#submit-task").click(function () {
        save_Task();
    });
});